import 'dart:async';

import 'package:cave_flutter/common/chat_rtc_manager.dart';
import 'package:get/get.dart';

import '../../../model/user_model.dart';
import '../../../network/whl_api.dart';
import '../../../utils/event_bus_utils.dart';
import '../../whl_main/whl_main_logic.dart';

enum CallMoreBtnType {
  cameraChange, //切换摄像头
  sound, //扬声器外音
  closeVoice, //静音
  gift, //礼物
  beauty //美颜
}

class Chat_callLogic extends GetxController {
  List callMoreBtnTitles = [
    {
      "image": "chat_cameraChange",
      "title": "切换",
      "type": CallMoreBtnType.cameraChange
    },
    {"image": "chat_videoMY", "title": "美颜", "type": CallMoreBtnType.beauty},
    {"image": "chat_gift", "title": "礼物", "type": CallMoreBtnType.gift},
    {
      "image": "chat_videoJY",
      "title": "静音",
      "type": CallMoreBtnType.closeVoice
    },
    {"image": "chat_videoMT", "title": "免提", "type": CallMoreBtnType.sound}
  ];

  bool isVideoCall = false;
  Timer? _timer;
  StreamSubscription? rtcStatusSubscription;

  List<RtcUserSession> remoteSessions = [];

  bool isSpeakerEnabled = false;
  bool isAudioEnabled = false;
  bool isFrontCamera = true;

  int uid = 0;

  UserModel? userModel;

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();

    setupSubscription();
    uid = ChatRTCManager.getInstance().myUid;
    userModel = ChatRTCManager.getInstance().userModel;
    isVideoCall = ChatRTCManager.getInstance().isVideoCall ?? false;
    isSpeakerEnabled = ChatRTCManager.getInstance().isSpeakerEnabled;
    isAudioEnabled = ChatRTCManager.getInstance().isAudioEnabled;
    isFrontCamera = ChatRTCManager.getInstance().isFrontCamera;
    remoteSessions = ChatRTCManager.getInstance().remoteSessions;
    setupMoreBtnData();
    if (ChatRTCManager.getInstance().isCallIng) {
      print("start time 222222");
      startTimer();
    }
    if (userModel == null) {
      getAllUserInfo();
    }
    update();
  }

  @override
  void onClose() {
    rtcStatusSubscription?.cancel();
    if (_timer != null && _timer!.isActive) {
      _timer!.cancel();
      _timer = null;
    }
    super.onClose();
  }

  setupSubscription() {
    rtcStatusSubscription =
        EventBusUtils.getInstance().eventBus.on<RtcStatus>().listen((event) {
      // All events are of type UserLoggedInEvent (or subtypes of it).
          print("start time");
      if (event.status == -1) {
        Get.back();
      } else {
        if (event.status == 1) {
          print("start time 111111");
          ChatRTCManager.getInstance().callTime = 0;
          startTimer();
        }
        remoteSessions = event.remoteSessions;
        update();
      }
    });
  }

  getAllUserInfo() {
    List allIds = [ChatRTCManager.getInstance().toAccountId];
    WhlApi.batchReplaceUserInfo.post(allIds).then((value) {
      if (value.isSuccess()) {
        List data = value.data ?? [];
        List<UserModel> models =
        data.map((e) => UserModel.fromJson(e)).toList();
        userModel = models.first;
        update();
      }
    });
  }

  startTimer() {
    if (_timer != null) {
      return;
    }
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      ChatRTCManager.getInstance().callTime++;
      update();
    });
  }

  setupMoreBtnData() {
    if (isVideoCall) {
      callMoreBtnTitles = [
        {
          "image": "chat_cameraChange",
          "title": "切换",
          "type": CallMoreBtnType.cameraChange
        },
        {
          "image": "chat_videoMY",
          "title": "美颜",
          "type": CallMoreBtnType.beauty
        },
        {"image": "chat_gift", "title": "礼物", "type": CallMoreBtnType.gift},
        {
          "image": "chat_videoJY",
          "title": "静音",
          "type": CallMoreBtnType.closeVoice
        },
        {"image": "chat_videoMT", "title": "免提", "type": CallMoreBtnType.sound}
      ];
    } else {
      callMoreBtnTitles = [
        {
          "image": "chat_videoJY",
          "title": "静音",
          "type": CallMoreBtnType.closeVoice
        },
        {"image": "chat_gift", "title": "礼物", "type": CallMoreBtnType.gift},
        {"image": "chat_videoMT", "title": "免提", "type": CallMoreBtnType.sound}
      ];
    }
  }

  void endCall() {
    ChatRTCManager.getInstance().stopCall();
    sendCallGDMessage(
        toAccountId: ChatRTCManager.getInstance().toAccountId,
        isVideoCall: isVideoCall,
        callTime: ChatRTCManager.getInstance().callTime);
    Get.back();
  }

  void moreBtnAction(CallMoreBtnType type) {
    if (type == CallMoreBtnType.cameraChange) {
      ChatRTCManager.getInstance().switchCamera(callBack: (value) {
        isFrontCamera = value;
        update();
      });
    } else if (type == CallMoreBtnType.closeVoice) {
      ChatRTCManager.getInstance().openCloseAudio(!isAudioEnabled,
          callBack: (value) {
        isAudioEnabled = value;
        update();
      });
    } else if (type == CallMoreBtnType.sound) {
      ChatRTCManager.getInstance().openCloseSpeakerphone(!isSpeakerEnabled,
          callBack: (value) {
        isSpeakerEnabled = value;
        update();
      });
    }
  }

  void backAction() {
    Get.back();
    final mainLogic = Get.find<WhlMainLogic>();
    mainLogic.showSmVideoView();
  }
}
